/**
 * 客户端专属（基于vue）
 */
import vueStat from 'stat/vue'

// 页面非刷新的跳转次数
let viewCount = 0;

export const GetSdkData = getData => dataList => {
	const sdkData = (data = getData()[0]) => ({
		actionType: data.type,
		pageName: data.page,
		target: data.target,
		
		// 没有路由或页面无跳转时
		// 且有上一个页面时
		// parentPage未取到赋值，手动赋值
		parentPage: (viewCount <= 1 && /^http/.test(data.parentPage) && data.other.pageChainMetaData[1] ? data.other.pageChainMetaData[1].statName : data.parentPage) || '/',
		pageFrom: data.other.pageStackMetaData.map(item => item.statName || '/').reverse(),
		actionParams: data.actionParams,
		pageParams: data.pageParams,
	})

	if (!Array.isArray(dataList)) return JSON.stringify([sdkData()])

	return JSON.stringify(dataList.map(item => sdkData(item)))
}

export let getSdkData = () => true

export default (router,
	{ 
		showConsole = false,
		// version = '',
		oncePageView = true,
		onceNodeView = true,
		metaPageName = '',
		metaPageParamsGet = '',
		pageEndOptions: { // 页面end相关
			pathFilter = [],
			h5ToClient = [],
		} = {},
		unRouter = false,
		statName = document.title,
	} = {}) => ({
	install(Vue) {
		Vue.prototype.$vueStat = vueStat

		let hostSdk
		try {
			hostSdk = require('host-sdk')
		} catch (err) {
			hostSdk = {
				stat(){},
				setStatFun(){},
				init(){},
				getInfo(){},
				versionVerify(){},
				uploadPageEndStatistics(){},
			}
		}

		const stat = (...value) => {
			showConsole && console.log('sdkData：', JSON.parse(value[0]), value[1])

			return hostSdk.stat(...value)
		}

		// 获取基础上报参数
		const getBaseData = () => Vue.prototype.$Stat._getPageViewData()

		// 格式化sdk需要的数据
		getSdkData = GetSdkData(getBaseData)

		// 设置参数
		vueStat.set({
			from: 'client',
			router,
			metaPageName,
			metaPageParamsGet,
			report(data, opt) {
				return stat(getSdkData(data), opt)
			},
			chainLength: 10,
			oncePageView,
			onceNodeView,
			unRouter,
			statName,
		})

		Vue.use(vueStat)

		// 页面停留时间 --------------------------------------------------------------------------
		let time = Date.now()
		let _time = 0
		let diff = 0
		const updateTime = () => {
			_time = Date.now()
			diff = _time - time
			time = _time

			return true
		}
		const getDiffData = (isSdk = false, _diff) => ({ pageName: JSON.parse(getSdkData())[0][isSdk ? 'pageName' : 'parentPage'], duration: _diff || diff })

		// 获取页面链参数
		const getChainParams = index => Vue.prototype.$Stat._route.getOwnPageChainParams(null, { index })[0]
		// console.log(getChainParams(0), getChainParams(1), Date.now())

		// 有路由的页面停留时间
		if (router) router.afterEach(to => setTimeout(() => viewCount++ && updateTime() && hostSdk.uploadPageEndStatistics(getDiffData()), 100))
		// href跳转的页面停留时间，根据页面链为sessionStorage存储判断
		else {
			const lastPage = getChainParams(1)

			if (lastPage && lastPage.date) hostSdk.uploadPageEndStatistics(
				getDiffData(
					false, 
					(getChainParams(0).date || Date.now()) - lastPage.date,
				), 
			)
		}

		// 获取当前路径
		const getPath = () => router ? router.currentRoute.path : window.location.pathname

		// 客户端生命周期 onPause ，在webview被遮盖或销毁时执行
		hostSdk.pause(() => {
			if (pathFilter.find(item => getPath().indexOf(item) > -1)) return

			updateTime() && hostSdk.uploadPageEndStatistics(getDiffData(true))
		})
		// -------------------------------------------------------------------------------------
		
		// 设置从客户端跳转到页面时 获取页面数据的方法
		hostSdk.setStatFun(() => {
			if (h5ToClient.find(item => getPath().indexOf(item) > -1)) updateTime() && hostSdk.uploadPageEndStatistics(getDiffData(true))

			return getSdkData(getBaseData())
		})

		// 在sdk初始化完成之前先缓存需要上报的数据
		// Vue.prototype.$Stat.options.cachePageReport = true

		// 版本控制
		// const ua = window.navigator.userAgent
		// const isAndroid = () => ua.toLowerCase().indexOf("android") > -1 || ua.toLowerCase().indexOf("linux") > -1
		// const _version = isAndroid() ? '5.46.1' : '5.64'

		// hostSdk.init(() => hostSdk.getInfo({
		// 	successCallback(res) {
		// 		const system = JSON.parse(res)

		// 		if (version) system.version = version

		// 		// 停止上报
		// 		if (!system.version) return Vue.prototype.$Stat.options.stopRouteReport = true

		// 		// 版本达到要求可上报
		// 		if (hostSdk.versionVerify(system.version, _version)) {
		// 			Vue.prototype.$Stat.options.cachePageReport = false

		// 			// 获取缓存的上报数据进行上报
		// 			Vue.prototype.$Stat.getCachePage().forEach(item => stat(getSdkData(item)))
		// 			Vue.prototype.$Stat.getCacheNode().forEach(item => stat(getSdkData(item)))
		// 		}
		// 	},
		// }))
	},
})
